package br.com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.bean.Pessoa;
import br.com.factory.ConnectionFactory;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class OtherServices {
	static ConnectionFactory banco;
	private static OtherServices instance;

	public static OtherServices getInstance() {
		if (instance == null) {
			banco = new ConnectionFactory();
			instance = new OtherServices(banco);
		}
		return instance;
	}
	
	public Connection connection;

	public OtherServices(ConnectionFactory banco) {
		this.connection = (Connection) banco.getConnection();
	}

	public OtherServices() {
		this.connection = (Connection) banco.getConnection();
	}
	
	public void cadastrarPessoa(Pessoa pessoa) {

		try {

			String sql = "INSERT INTO tb_pessoa (nome, matricula, "
					+ "senha, tipo) VALUES (?,?,?,?)";

			PreparedStatement stmt = (PreparedStatement) connection
					.prepareStatement(sql);

			stmt.setString(1, pessoa.getNome());
			stmt.setString(2, pessoa.getMatricula());
			stmt.setString(3, pessoa.getSenha());
			stmt.setString(4, pessoa.getTipo());
			
			stmt.execute();
			stmt.close();

		} catch (SQLException sqle) {
			throw new RuntimeException(sqle);
		}

	}
	
	public boolean logarUsuario(Pessoa pessoa){
		
		boolean login = false;
		
		try {
			String sql = "SELECT * FROM tb_pessoa WHERE matricula = ? AND senha = ?";
			
			PreparedStatement stmt = (PreparedStatement) connection
					.prepareStatement(sql);
			
			stmt.setString(1, pessoa.getMatricula());
			stmt.setString(2, pessoa.getSenha());
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()){
				login = true;
			} 
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return login;
	}
	
	public String pegarTipo(String string){
		
		String tipo = null;
		
		try {
			String sql = "SELECT tipo FROM tb_pessoa WHERE matricula = ?";
			PreparedStatement stmt = (PreparedStatement) connection
					.prepareStatement(sql);
			stmt.setString(1, string);
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()){
				tipo = rs.getString("tipo");
			} 
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return tipo;
	}
}
